
import requests
import json
import sys
if sys.version_info < (3, 0):
    from urlparse import urljoin  # noqa
else:
    from urllib.parse import urljoin  # noqa
    from urllib.parse import urlencode


def _chk_jsonrep(ret):
    if ret.status_code == 200:
        try:
            reponse = json.loads(ret.text)
        except expression as identifier:
            return (False, ret)
        return (reponse.get("r") == 0, reponse)
    else:
        return (False, ret)


class HeyzfLogin:

    BASE_URL = "https://api.heyzf.com"

    @classmethod
    def post_acctoken(cls, usr, pwd):

        params_dic = {
            "username": usr,
            "password": pwd,
        }
        params = urlencode(params_dic)
        furl = urljoin(cls.BASE_URL, "/v1/oauth/login/userpwd")

        header = {
            "Content-Type": "application/json"
        }
        ret = requests.post(furl, json.dumps(
            params_dic, sort_keys=True, indent=4),
            headers=header, verify=False)
        return _chk_jsonrep(ret)

    @classmethod
    def post_refreshtoken(cls, gid, rftoken):
        params_dic = {
            "gid": gid,
            "refresh_token": rftoken
        }
        params = urlencode(params_dic)
        furl = urljoin(cls.BASE_URL, "/v1/oauth/token?%s") % params
        ret = requests.get(furl, verify=False)
        return _chk_jsonrep(ret)

    @classmethod
    def get_heyzfusr(cls, gid):
        furl = urljoin(cls.BASE_URL, "/v1/oauth/user")
        headers = {
            "X-D-GID": str(gid)
        }
        ret = requests.get(furl, verify=False, headers=headers)
        return _chk_jsonrep(ret)
